package com.fengxu.gamescript.ui.cloud

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ListView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSONArray
import com.fengxu.gamescript.R
import com.fengxu.gamescript.data.Conf
import com.fengxu.gamescript.data.GlobalData
import com.fengxu.gamescript.data.po.NetScript
import com.fengxu.gamescript.provide.ProviderFactory
import com.fengxu.gamescript.ui.base.BaseActivity
import com.fengxu.gamescript.ui.main.MainActivity
import com.fengxu.gamescript.util.CommonUtils
import com.github.onlynight.library.lsearchview.LSearchView
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.xuexiang.xui.widget.toast.XToast
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.sdk27.coroutines.onEditorAction

class CloudMusicActivity : BaseActivity() {

    /**
     * 搜索框
     */
    private val mSearchView: LSearchView by lazy {
        findViewById(R.id.cloud_music_searchView)
    }

    /**
     * 云服务次数显示框
     */
    private val cloudTimesView: TextView by lazy {
        findViewById(R.id.cloud_music_times)
    }

    /**
     * 智能刷新布局
     */
    private val smartRefreshLayout: SmartRefreshLayout by lazy {
        findViewById(R.id.cloud_music_smartRefresh)
    }

    /**
     * 脚本列表
     */
    private val scriptRecyclerView: RecyclerView by lazy {
        findViewById(R.id.cloud_music_scriptList)
    }

    /**
     * 当前脚本页数
     */
    private var mPage:Int = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_cloud_music)
        backMode = BackMode.Two
        initView()
    }

    /**
     * 初始化View
     */
    private fun initView() {
        // 添加退出事件
        findViewById<View>(R.id.cloud_music_back).onClick { finish() }
        // 设置云服务次数
        cloudTimesView.text = GlobalData.user!!.remainTimes.toString()
        // 初始化搜索功能
        initSearchFunc()
        // 设置开启加载更多功能
        smartRefreshLayout.setEnableLoadMore(true)
        // 初始化脚本列表
        CommonUtils.toastDialog(this,content = "该功能正在修复中，敬请期待...",cancelable = false
            ,onPositive = {
                finish()
            })
        // 添加刷新脚本事件
        smartRefreshLayout.setOnRefreshListener {
            mPage = 1
            getNetScriptList({
                // 成功
                (scriptRecyclerView.adapter as NetScriptListAdapter).run {
                    datas = it
                    notifyDataSetChanged()
                }
                smartRefreshLayout.finishRefresh()
            },{
                // 失败
                smartRefreshLayout.finishRefresh()
                XToast.error(this,it).show()
            })
        }
        // 添加下拉加载下一页事件
        smartRefreshLayout.setOnLoadMoreListener {
            mPage += 1
            getNetScriptList({
                // 成功
                val adapter = scriptRecyclerView.adapter as NetScriptListAdapter
                val startChangeIndex = adapter.datas.size - 1
                adapter.datas.addAll(it)
                adapter.notifyItemRangeInserted(startChangeIndex, it.size)
                smartRefreshLayout.finishLoadMore()
            },{
                // 失败
                smartRefreshLayout.finishLoadMore()
                XToast.error(this,it).show()
            })
        }
    }

    /**
     * 初始化搜索功能
     */
    private fun initSearchFunc() {
        // 添加点击搜索出现搜索框
        find<View>(R.id.cloud_music_search).onClick {
            mSearchView.visibility = View.VISIBLE
            mSearchView.showWithAnim()
            mSearchView.searchEdit.requestFocus()
        }
        // 配置搜索历史列表
        val historyListView = findViewById<ListView>(R.id.cloud_music_historyList)
        historyListView.adapter = ScriptSearchHistoryListAdapter(this).apply {
            clickItemEvent = { mSearchView.searchEdit.setText(it) }
        }
        // 设置清空搜索记录
        val clearAllSearchView = findViewById<View>(R.id.cloud_music_clearHistory)
        clearAllSearchView.onClick { Conf.getConf().removeAllSearchHistory() }
        // 配置清空搜索历史在三条记录以上时触发
        val setClearAllHistoryView =  { clearAllSearchView.isVisible = Conf.getConf().scriptSearchHistory.size >= 3 }
        setClearAllHistoryView()
        // 设置历史记录变更事件
        Conf.getConf().setSearchHistoryChanged {
            setClearAllHistoryView()
            // 通知列表更新数据，其中重写了，包含保存历史
            (historyListView.adapter as ScriptSearchHistoryListAdapter).notifyDataSetChanged()
        }
        // 添加搜索事件
        mSearchView.searchEdit.imeOptions = EditorInfo.IME_ACTION_SEARCH
        mSearchView.searchButton.onClick { searchNetScript(mSearchView.searchEdit.text.toString()) }
        mSearchView.searchEdit.onEditorAction { _, action, _ ->
            if (action == EditorInfo.IME_ACTION_SEARCH) {
                searchNetScript(mSearchView.searchEdit.text.toString())
            }
        }
    }

    /**
     *搜索网络脚本
     * @param kw 关键字
     */
    private fun searchNetScript(kw: String) {
        if(kw.isEmpty()){
            CommonUtils.toastDialog(this,content = "搜索关键字不能为空!")
            return
        }
        mSearchView.setSearching(true)
        val loadingDialog = CommonUtils.loadingDialog(this, content = "搜索中...")
        Conf.getConf().addSearchHistory(kw)
        doAsync {
            val result = ProviderFactory.dataProvider.searchMusic(1, kw)
            if(result == null){
                runOnUiThread {
                    loadingDialog.dismiss()
                    mSearchView.setSearching(false)
                    CommonUtils.toastDialog(this@CloudMusicActivity,content = "网络连接失败!")
                }
                return@doAsync
            }
            when(result.code){
                200 -> {
                    val scriptList = JSONArray.parseArray(result.data.toString())
                        .toJavaList(NetScript::class.java)
                    runOnUiThread {
                        scriptRecyclerView.adapter = NetScriptListAdapter(this@CloudMusicActivity,scriptList)
                        mSearchView.searchEdit.setText("")
                        mSearchView.hideWithAnim()
                    }
                }
                else -> {
                    CommonUtils.toastDialog(this@CloudMusicActivity,content = result.msg)
                }
            }
            runOnUiThread {
                loadingDialog.dismiss()
                mSearchView.setSearching(false)
                // 更新云次数
                if(result.remainTimes != null){
                    GlobalData.user!!.remainTimes = result.remainTimes
                    cloudTimesView.text = result.remainTimes.toString()
                }
            }
        }

    }

    /**
     * 初始化脚本列表
     */
    private fun initScriptList(){
        // 清除已下载脚本中已经不存在了的
        Conf.getConf().clearNotExistScript()
        doAsync { Conf.saveConf(this@CloudMusicActivity) }
        // 初始化布局规则
        scriptRecyclerView.layoutManager = LinearLayoutManager(this).apply {
            orientation = LinearLayoutManager.VERTICAL
        }
        // 设置适配器
        val adapter = NetScriptListAdapter(this, mutableListOf()).apply {
            cloudTimesChanged= {
                GlobalData.user!!.remainTimes = it
                cloudTimesView.text = it.toString()
            }
        }
        scriptRecyclerView.adapter = adapter
        // 获取初始页数据
        getNetScriptList({
            adapter.datas = it
            adapter.notifyDataSetChanged()
        },{
            // 失败
            XToast.error(this,it).show()
        })
    }

    /**
     * 获取网络脚本列表
     * @param onSuccess 成功的回调
     */
    private inline fun getNetScriptList(
        crossinline onSuccess: (MutableList<NetScript>)->Unit,
        crossinline onFail: (String)->Unit
    ){
        val pageCount:Int = 10
        val loadingDialog = CommonUtils.loadingDialog(this)
        doAsync {
            val result = ProviderFactory.dataProvider
                .getMusicList(1, (mPage - 1) * pageCount, pageCount)
            if(result == null){
                runOnUiThread {
                    loadingDialog.dismiss()
                    onFail.invoke("网络连接失败!")
                }
                return@doAsync
            }
            when(result.code){
                200 -> {
                    val scriptList = JSONArray.parseArray(result.data.toString())
                        .toJavaList(NetScript::class.java)
                    runOnUiThread {
                        onSuccess.invoke(scriptList)
                        if(result.remainTimes != null){
                            GlobalData.user!!.remainTimes = result.remainTimes
                            cloudTimesView.text = result.remainTimes.toString()
                        }
                    }
                }
                else ->{ onFail.invoke(result.msg) }
            }
            runOnUiThread { loadingDialog.dismiss() }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        startActivity(Intent(this, MainActivity::class.java))
    }

}